package com.raychi.demo.servlet.product;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.raychi.demo.entity.Product;
import com.raychi.demo.util.JdbcUtil;
import com.raychi.demo.util.ProductUtil;

public class ProductUpdateServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		int id = Integer.parseInt(req.getParameter("id"));
		Product product = getProductById(id);
		req.setAttribute("product", product);
		req.getRequestDispatcher("/product/updateProduct.jsp").forward(req, resp);
	}
	
	private Product getProductById(int id) {
		Product product = null;
		Connection conn = null;
		try {
			conn = JdbcUtil.getConnection();
			Statement st = conn.createStatement();
			String sql = "select * from product where id=" + id;
			ResultSet rs = st.executeQuery(sql);
			while (rs.next()) {
				product = ProductUtil.createProduct(rs);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
		return product;
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try{
			req.setCharacterEncoding("utf-8");
			String name = req.getParameter("name");
			float price = Float.valueOf(req.getParameter("price"));
			int id = Integer.valueOf(req.getParameter("id"));
			updateProduct(name, price, id);
			resp.sendRedirect(req.getContextPath()+"/product/");
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	private void updateProduct(String name, float price, int id) throws SQLException,
			ClassNotFoundException {
		Connection conn = JdbcUtil.getConnection();
		String sql = "update product set name = ?,price = ? where id =?"; 	
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, name);
		ps.setFloat(2, price);
		ps.setInt(3, id);
		ps.executeUpdate();
		conn.commit();
	}

}
